package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.GregorianCalendar;
import it.univaq.mancoosi.injectors.systemconfiguration.managers.DesktopDbManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;
import it.univaq.mancoosi.mancoosimm.File;

public class UbuntuDesktopDbManager extends DesktopDbManager {
	
	protected String desktopDbPath = "/usr/share/applications";
	
	public UbuntuDesktopDbManager(){
		super();
	}

	public static DesktopDbManager getInstance() {
		if (INSTANCE == null)
			INSTANCE = new UbuntuDesktopDbManager();
		return INSTANCE;
	}
	
	@Override
	public void createDesktopDbFromSystem() {

		try {
			desktopDB.setEnv(UbuntuEnvironmentManager.getInstance().getEnvironment());
			UbuntuEnvironmentManager.getInstance().getEnvironment().setDesktopDb(desktopDB);
			
			java.io.File desktopDbFile = new java.io.File(desktopDbPath);

			if(desktopDbFile.exists()){
				File desktopDbModelFile = UbuntuFileSystemManager.getInstance()
				.createFile(desktopDbPath);

				desktopDB.setApplications(desktopDbModelFile);

				desktopDB.setMtime(getMtimeUtil());
			}			

		} catch (Exception err) {
			err.printStackTrace();
		}		
	}

	@Override
	public void synchronize() throws IOException {
		try {
			java.io.File desktopDbFile = new java.io.File(desktopDbPath);
			if(desktopDbFile.exists()){
				if(UbuntuEnvironmentManager.getInstance().getEnvironment().getDesktopDb() == null){
					createDesktopDbFromSystem();
				}else{
					//update mtime
					UbuntuEnvironmentManager.getInstance().getEnvironment().getDesktopDb().setMtime(getMtimeUtil());
				}				
			}else{
				if(UbuntuEnvironmentManager.getInstance().getEnvironment().getDesktopDb() != null){
					UbuntuEnvironmentManager.getInstance().getEnvironment().setDesktopDb(null);
					UbuntuFileSystemManager.getInstance().deleteFile(desktopDbPath);					
				}
			}

		} catch (Exception err) {
			err.printStackTrace();
		} 

	}
	
	protected Date getMtimeUtil(){

		String[] mTime;

		try {
			java.io.File mimeInfo = new java.io.File("/usr/share/applications/mimeinfo.cache");
			if (!mimeInfo.exists()) return null;

			String[] cmd = {"/bin/sh","-c","ls -l /usr/share/applications/mimeinfo.cache"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd);	

			mTime = input.readLine().split(" ");

			GregorianCalendar calendar = new GregorianCalendar();
			calendar.set(new Integer(mTime[5].split("-")[0]),
					(new Integer(mTime[5].split("-")[1]) -1),
					new Integer(mTime[5].split("-")[2]),
					new Integer(mTime[6].split(":")[0]),
					new Integer(mTime[6].split(":")[1]));

			return calendar.getTime();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;		
	}	
}
